(function (window) {
    const chaoge = {

        get: function (url, data, success) {
            const xhr = new XMLHttpRequest();

            if (Object.prototype.toString.call(url).slice(8, -1) === 'Object') {
                const option = url;
                url = option.url;
                data = option.data;
                success = option.success;
            }

            if (!!data) {
                const type = Object.prototype.toString.call(data).slice(8, -1)
                switch (type) {
                    case 'String':
                        url += '?' + data;
                        break;
                    case 'Function':
                        success = data;
                        data = undefined;
                        break;
                    case 'Object':
                        url += '?' + JSON.stringify(data).replace(/:/g, "=").replace(/"/g, '').replace(/,/g, '&').match(/\{([^)]*)\}/)[1]
                        break;
                }
            }
            xhr.open('get', url);
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status == 200) {
                    success.call(xhr);
                }
            }
        },

        post: function (url, data, success) {
            const xhr = new XMLHttpRequest();

            if (Object.prototype.toString.call(url).slice(8, -1) === 'Object') {
                const option = url;
                url = option.url;
                data = option.data;
                success = option.success;
            }

            if (!!data) {
                const type = Object.prototype.toString.call(data).slice(8, -1);
                switch (type) {
                    case 'Function':
                        success = data;
                        data = undefined;
                        break;
                    case 'Object':
                        data = JSON.stringify(data).replace(/:/g, "=").replace(/"/g, '').replace(/,/g, '&').match(/\{([^)]*)\}/)[1];
                        break;
                }
            }

            xhr.open('post', url);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(data || null);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status == 200) {
                    success.call(xhr);
                }
            }
        },
        
        ajax: function (options) {

            switch (options.type) {
                case 'get':
                    this.get(options)
                    break;
                case 'post':
                    this.post(options)
                    break;
                default:
                    break;
            }
        }
    }
    window.$ = window.cg = chaoge;
})(window);